package com.cloud.media.common.utils;

import java.lang.reflect.Field;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.sql.DataSource;

import org.apache.commons.lang.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * 工具类，基于Redis生成数据库主键序列
 * 
 * @author taominglong
 *
 */
public class RedisKeyHelper {
	/**
	 * 基于Redis生成数据库主键
	 * 
	 * @param clazz
	 * @return
	 */
	public static long genereateKey(Class<?> clazz) {
		//TODO:先从Redis中获取对应的主键信息
		long max = 0;
		synchronized (clazz) {
			String tableName = null, idFieldName = null;
			Table[] ts = clazz.getDeclaredAnnotationsByType(Table.class);
			if (ts != null && ts.length == 1) {
				Table table = ts[0];
				tableName = table.name();
			}
			if (StringUtils.isEmpty(tableName))
				throw new RuntimeException("未能解析到实体类对应的表名，请检查实体类是否包含@Table注解。");
			Field[] fields = clazz.getDeclaredFields();
			for (Field f : fields) {
				Id[] ids = f.getAnnotationsByType(Id.class);
				if (null != ids && ids.length == 1) {
					Column[] cs = f.getAnnotationsByType(Column.class);
					if (null != cs && cs.length == 1) {
						idFieldName = cs[0].name();
					} else {
						idFieldName = f.getName();
					}
				}
			}
			if (StringUtils.isEmpty(idFieldName))
				throw new RuntimeException("未能解析到实体类对应的主键字段，请检查是否包含@Id， @Column注解。");
			DataSource ds = SpringBeanHelper.getBean(DataSource.class);
			JdbcTemplate jdbcTemplate = new JdbcTemplate(ds);
			List<Long> ids = jdbcTemplate.queryForList("select max(" + idFieldName + ") from " + tableName, Long.class);
			if(null != ids && ids.size() == 1 && null != ids.get(0)){
				max = ids.get(0);
			}else{
				max = 0;
			}
			//TODO:以表名放入到redis中，
		}
		return max + 1;
	}

}
